from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from urllib2 import URLError, HTTPError
import urllib2
import xml.etree.ElementTree as ET

class RSS(webapp.RequestHandler):    
    
    def get(self):
        self.response.headers['Content-Type'] = 'text/xml'
        #self.response.out.write('RSS feed')
        url=self.request.get('url')
        if(url==None or url==""):
            url="http://timesofindia.indiatimes.com/rssfeedstopstories.cms"
        if(url!=""):
                try:
                    request = urllib2.Request(url)
                    opener = urllib2.build_opener()   
                    #request.add_header('User-Agent','kjnTOIHEAD/1.0 +http://toihead.appspot.com/') 
                    rssfeed = opener.open(request).read()
                    #print rssfeed
                    doc = ET.fromstring(rssfeed)
                    links = doc.getiterator("link")
                    for link in links:
                        link.text = 'http://toihead.appspot.com/?url='+link.text
                    docs = ET.tostring(doc)
                    self.response.out.write(docs)
                except HTTPError,e: 
                    self.response.write( "Error:"+ e.code)
                except URLError, e:
                    self.response.write( 'We failed to reach a server.')
                    self.response.write( 'Reason: '+e.reason)


class RSS2(webapp.RequestHandler):
    def get (self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('TEST')
        


application = webapp.WSGIApplication([('/rss', RSS),('/rss/test',RSS2)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
